﻿using IntoTheVoid.Units;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Input;

namespace IntoTheVoid.Models
{
	public class BaseInfoContentModel : SingletonBase<BaseInfoContentModel>
	{

		private string jsonName => AppDomain.CurrentDomain.BaseDirectory + "BaseConfig.json";

		private readonly FileHelper fileHelper;

		private JObject baseInfo;
		
		public BaseInfoContentModel()
		{
			fileHelper = new FileHelper(jsonName);
			baseInfo = fileHelper.ReadFile() ?? new JObject();
		}

		public T GetValue<T>(string key, T defaultValue = default)
		{
			baseInfo = baseInfo ?? new JObject();
		
			if (baseInfo.TryGetValue(key, out JToken value))
			{
				return value.ToObject<T>();
			}
			
			if(defaultValue != null)
				SetValue(key, defaultValue);

			return defaultValue;
		}

		public void SetValue(string key, object newValue)
		{
			baseInfo = baseInfo ?? new JObject();
		
			if (baseInfo.ContainsKey(key))
			{
				baseInfo[key] = JToken.FromObject(newValue);
//				LogHelper.Log($"Value for key '{key}' updated to '{newValue}'.");
					
			}
			else
			{
				baseInfo[key] = JToken.FromObject(newValue);
//				LogHelper.Log($"Key '{key}' not found in JSON file.");
			}
			
			fileHelper.SaveFile(baseInfo);

		}
		public void DeleteFile()
		{
			if (File.Exists(jsonName))
			{
				File.Delete(jsonName);
			}
			baseInfo = new JObject();
		}

	}
}
